package com.djf.controller;

import com.djf.entity.Order;
import com.djf.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 订单测试控制器
 * 专门用于测试分表功能，允许手动指定创建时间
 * 
 * @author djf
 * @since 2024-01-20
 */
@Slf4j
@RestController
@RequestMapping("/api/test/orders")
@RequiredArgsConstructor
public class OrderTestController {

    private final OrderService orderService;

    /**
     * 创建测试订单（可指定创建时间）
     * 
     * @param tenantId 租户ID
     * @param userId 用户ID
     * @param productName 商品名称
     * @param productPrice 商品价格
     * @param quantity 购买数量
     * @param createTime 创建时间（可选，格式：yyyy-MM-dd HH:mm:ss）
     * @return 创建结果
     */
    @PostMapping("/create")
    public Map<String, Object> createTestOrder(
            @RequestParam Long tenantId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "测试商品") String productName,
            @RequestParam(defaultValue = "999.00") BigDecimal productPrice,
            @RequestParam(defaultValue = "1") Integer quantity,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setTenantId(tenantId);
            order.setUserId(userId);
            order.setProductName(productName);
            order.setProductPrice(productPrice);
            order.setQuantity(quantity);
            order.setTotalAmount(productPrice.multiply(BigDecimal.valueOf(quantity)));
            order.setOrderStatus(Order.OrderStatus.PENDING_PAYMENT.getCode());
            order.setPaymentMethod("测试支付");
            order.setShippingAddress("测试地址");
            order.setRemark("测试订单 - 手动指定时间");
            
            // 如果指定了创建时间，则使用指定时间，否则使用当前时间
            if (createTime != null) {
                order.setCreateTime(createTime);
                log.info("使用指定的创建时间：{}", createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } else {
                order.setCreateTime(LocalDateTime.now());
                log.info("使用当前时间作为创建时间");
            }
            
            Order createdOrder = orderService.createOrder(order);
            
            result.put("success", true);
            result.put("message", "测试订单创建成功");
            result.put("data", createdOrder);
            result.put("shardingTable", "order_" + createdOrder.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMM")));
            
            log.info("测试订单创建成功，订单号：{}，分表到：order_{}", 
                    createdOrder.getOrderNo(), 
                    createdOrder.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMM")));
                    
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试订单创建失败：" + e.getMessage());
            log.error("测试订单创建失败", e);
        }
        return result;
    }

    /**
     * 批量创建测试订单（指定不同月份）
     * 
     * @param tenantId 租户ID
     * @param userId 用户ID
     * @param count 每个月创建的订单数量
     * @return 创建结果
     */
    @PostMapping("/batch-create")
    public Map<String, Object> batchCreateTestOrders(
            @RequestParam Long tenantId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "2") Integer count) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 定义测试的月份
            LocalDateTime[] testMonths = {
                LocalDateTime.of(2025, 1, 15, 10, 30),
                LocalDateTime.of(2025, 2, 20, 14, 45),
                LocalDateTime.of(2025, 3, 10, 9, 15),
                LocalDateTime.of(2025, 4, 25, 16, 20),
                LocalDateTime.of(2025, 5, 8, 11, 10),
                LocalDateTime.of(2025, 6, 18, 15, 30)
            };
            
            int totalCreated = 0;
            Map<String, Integer> shardingStats = new HashMap<>();
            
            for (LocalDateTime baseTime : testMonths) {
                for (int i = 0; i < count; i++) {
                    Order order = new Order();
                    order.setOrderNo(generateOrderNo());
                    order.setTenantId(tenantId);
                    order.setUserId(userId + i); // 不同用户ID
                    order.setProductName("测试商品" + (i + 1));
                    order.setProductPrice(BigDecimal.valueOf(1000 + i * 100));
                    order.setQuantity(i + 1);
                    order.setTotalAmount(order.getProductPrice().multiply(BigDecimal.valueOf(order.getQuantity())));
                    order.setOrderStatus(Order.OrderStatus.PENDING_PAYMENT.getCode());
                    order.setPaymentMethod("批量测试支付");
                    order.setShippingAddress("批量测试地址");
                    order.setRemark("批量测试订单 - " + baseTime.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
                    
                    // 在基础时间上随机加几分钟
                    LocalDateTime createTime = baseTime.plusMinutes(i * 10);
                    order.setCreateTime(createTime);
                    
                    orderService.createOrder(order);
                    totalCreated++;
                    
                    String shardingTable = "order_" + createTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
                    shardingStats.put(shardingTable, shardingStats.getOrDefault(shardingTable, 0) + 1);
                }
            }
            
            result.put("success", true);
            result.put("message", "批量测试订单创建成功");
            result.put("totalCreated", totalCreated);
            result.put("shardingStats", shardingStats);
            
            log.info("批量测试订单创建成功，总计：{}条，分表统计：{}", totalCreated, shardingStats);
                    
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量测试订单创建失败：" + e.getMessage());
            log.error("批量测试订单创建失败", e);
        }
        return result;
    }

    /**
     * 创建指定月份的测试订单
     * 
     * @param year 年份
     * @param month 月份
     * @param day 日期
     * @param tenantId 租户ID
     * @param userId 用户ID
     * @return 创建结果
     */
    @PostMapping("/create-by-month")
    public Map<String, Object> createOrderByMonth(
            @RequestParam Integer year,
            @RequestParam Integer month,
            @RequestParam(defaultValue = "15") Integer day,
            @RequestParam Long tenantId,
            @RequestParam Long userId) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime createTime = LocalDateTime.of(year, month, day, 10, 30, 0);
            
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setTenantId(tenantId);
            order.setUserId(userId);
            order.setProductName("指定月份测试商品");
            order.setProductPrice(BigDecimal.valueOf(1999.00));
            order.setQuantity(1);
            order.setTotalAmount(order.getProductPrice());
            order.setOrderStatus(Order.OrderStatus.PENDING_PAYMENT.getCode());
            order.setPaymentMethod("指定月份测试支付");
            order.setShippingAddress("指定月份测试地址");
            order.setRemark(String.format("指定月份测试订单 - %d年%02d月", year, month));
            order.setCreateTime(createTime);
            
            Order createdOrder = orderService.createOrder(order);
            
            result.put("success", true);
            result.put("message", "指定月份测试订单创建成功");
            result.put("data", createdOrder);
            result.put("shardingTable", "order_" + createTime.format(DateTimeFormatter.ofPattern("yyyyMM")));
            
            log.info("指定月份测试订单创建成功，订单号：{}，分表到：order_{}", 
                    createdOrder.getOrderNo(), 
                    createTime.format(DateTimeFormatter.ofPattern("yyyyMM")));
                    
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "指定月份测试订单创建失败：" + e.getMessage());
            log.error("指定月份测试订单创建失败", e);
        }
        return result;
    }

    /**
     * 获取测试接口说明
     * 
     * @return 接口说明
     */
    @GetMapping("/help")
    public Map<String, Object> getTestHelp() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "订单分表测试接口说明");
        
        Map<String, Object> apis = new HashMap<>();
        apis.put("创建测试订单", "POST /api/test/orders/create?tenantId=1&userId=1001&createTime=2024-01-15 10:30:00");
        apis.put("批量创建测试订单", "POST /api/test/orders/batch-create?tenantId=1&userId=1001&count=3");
        apis.put("指定月份创建订单", "POST /api/test/orders/create-by-month?year=2024&month=3&tenantId=1&userId=1001");
        apis.put("查看帮助", "GET /api/test/orders/help");
        
        result.put("apis", apis);
        
        Map<String, String> examples = new HashMap<>();
        examples.put("创建1月订单", "POST /api/test/orders/create?tenantId=1&userId=1001&productName=iPhone15&productPrice=6999&createTime=2024-01-15 10:30:00");
        examples.put("创建3月订单", "POST /api/test/orders/create?tenantId=2&userId=1002&productName=MacBook&productPrice=12999&createTime=2024-03-20 14:45:00");
        examples.put("创建6月订单", "POST /api/test/orders/create-by-month?year=2024&month=6&tenantId=3&userId=1003");
        
        result.put("examples", examples);
        
        return result;
    }

    /**
     * 生成订单号
     * 
     * @return 订单号
     */
    private String generateOrderNo() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        return "TEST" + timestamp + uuid.toUpperCase();
    }
}